//
//  KLMainViewController.swift
//  新浪微博
//
//  Created by WTFKL on 17/8/4.
//  Copyright © 2017年 WTF. All rights reserved.
//

import UIKit

class KLMainViewController: UITabBarController {
  fileprivate  lazy var compoesBtn : UIButton = UIButton().createCustomButton(title: nil, imageName: "tabbar_compose_button", state: .normal, setForImageOrBgImage: .bgImage);

    override func viewDidLoad() {
        super.viewDidLoad()

        setupChildViewController();
        setupComposeBtn();
    }
    
    

    
}

private extension KLMainViewController {
    
      ///初始化 撰写按钮
    func setupComposeBtn(){
        
        let count = viewControllers?.count;
        
        let btnW = CGFloat(tabBar.frame.size.width) / CGFloat(count!) - 1 ;
        
        compoesBtn.frame = tabBar.bounds.insetBy(dx: 2*btnW, dy: 0);
        
        compoesBtn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for: .normal);
        
        tabBar.addSubview(compoesBtn);
    }
    
      /// 添加子控制器
      func setupChildViewController() {
        guard let path = Bundle.main.path(forResource: "main.json", ofType: nil),
                let data = NSData(contentsOfFile: path),
                let arrayM = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [[String : Any]]
        else {
            return;
        }
       
        var arrayVc = [UIViewController]();
        
        for dict in arrayM! {
            arrayVc.append(createController(dict: dict));
        }
        
        viewControllers = arrayVc;
    }
    
     func createController(dict : [String : Any]) -> UIViewController {
        guard let className = dict["className"] as? String ,
                  let titleName = dict["titleName"] as? String,
                  let imageName = dict["imageName"] as? String,
                  let visitDict = dict["visitInfo"] as? [String : String],
                  let cls = NSClassFromString(Bundle.main.namespace + "." + className) as? KLBaseViewController.Type else {
                  
                    return UIViewController();
        }
        
        let vc = cls.init();
        vc.visitInfo = visitDict;
        vc.title = titleName;
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName);
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_highlighted")?.withRenderingMode(.alwaysOriginal);
        
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.orange], for: .selected);
        let nav = KLNavigationController(rootViewController: vc);
        
        
        return nav;
        
    }
    
}
